﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using WinnerCMS.BLL;
using WinnerCMS.BLL.PageFactory;
using WinnerCMS.BLL.PageFactory.Pages;
using WinnerCMS.BLL.PageFactory.TagModule;
using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.WebFactory
{
    public class ArticleShow : PublicPage<Article>
    {
        /// <summary>
        /// 文章Id
        /// </summary>
        private int ArticleId
        {
            get { return Convert.ToInt32(Page.RouteData.Values["ID"]); }
        }

        protected int PageNo
        {
            get { return Convert.ToInt32(Page.RouteData.Values["PageNo"]); }
        }



        public ArticleShow()
        {

        }

        #region 重写事件
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);




        }
        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.Page_Load);

        }
        #endregion

        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (this.Model == null)
            {
                Response.Write("数据不存在或者被管理员删除");
                Response.End();
            }
            else
            {
                CategoryId = this.Model.CategoryId;
            }
        }

        #region 内容处理
        /// <summary>
        /// 内容处理
        /// </summary>
        /// <param name="winner"></param>
        private void ArticleContext(StringBuilder winner)
        {
            IList<string> matchresult = TagEngine.TagCollection(winner.ToString(), "Context");
            foreach (string nextmatch in matchresult)
            {
                winner.Replace(nextmatch, ContextBuilder(MyString.GetInnerString(nextmatch, "<TW:Context>", "</TW:Context>"), this.PageNo));
            }

        }

        private static readonly Regex HuanHang = new Regex(@"<br\s*?/*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        /// <summary>
        /// 内容处理
        /// </summary>
        /// <param name="contextTemplate"></param>
        /// <param name="pageno"></param>
        /// <returns></returns>
        private string ContextBuilder(string contextTemplate, int pageno)
        {
            StringBuilder tempStrBuilder = new StringBuilder(contextTemplate);

            string strContent = this.Model.Content;

            #region 文章分页
            if (strContent.Contains("@Next@"))//如果使用了手工分页标记
            {
                string[] strArr = strContent.Split(new[] { "@Next@" }, StringSplitOptions.RemoveEmptyEntries);

                if (strArr.Length > 1)
                {
                    BLL.PageFactory.HtmlFactory.UrlPager o = new BLL.PageFactory.HtmlFactory.UrlPager();
                    {
                        //CMSConfig config = CMSConfig.Instance();
                        //if (config.UrlRewrite)
                        //{
                        //    o.EnableUrlRewrite = true;
                        //}
                        o.PageNo = pageno;
                        o.PageSize = 1;
                        o.RecordCount = strArr.Length;
                        o.CssClass = "pager";
                        tempStrBuilder.Replace("@Page@", o.ToString());
                    }

                }
                else
                    tempStrBuilder.Replace("@Page@", "");

                if (this.Model.Rank == 0)
                {
                    tempStrBuilder.Replace("@Content@", strArr[pageno - 1]); //当前页的问题内容
                }
                else
                {
                    tempStrBuilder.Replace("@Content@", "<div id=\"ShowContent\"></div>"); //当前页的问题内容
                }

            }
            else
            {
                CMSConfig config = CMSConfig.Instance();
                if (config.Article.AutoCutPage)//没有手工分页但使用了自动分页配置
                {
                    string[] strArr = HuanHang.Split(strContent);

                    BLL.PageFactory.HtmlFactory.UrlPager o = new BLL.PageFactory.HtmlFactory.UrlPager();
                    {
                        //if (config.UrlRewrite)
                        //{
                        //    o.EnableUrlRewrite = true;
                        //}
                        o.PageNo = pageno;
                        o.PageSize = ArticleCommon.BrNum;
                        o.RecordCount = strArr.Length;
                        o.CssClass = "pager";
                        tempStrBuilder.Replace("@Page@", o.ToString());
                    }

                    if (this.Model.Rank == 0)
                    {
                        StringBuilder sbContent = new StringBuilder();
                        int temp = ((pageno - 1) * ArticleCommon.BrNum);
                        int maxIndex = temp + ArticleCommon.BrNum;
                        if (maxIndex > strArr.Length)
                        {
                            maxIndex = strArr.Length;
                        }
                        for (int I = temp; I < maxIndex; I++)
                        {
                            sbContent.Append(strArr[I]);
                            sbContent.Append("<br>");
                        }
                        tempStrBuilder.Replace("@Content@", sbContent.ToString()); //当前页的问题内容
                    }
                    else
                    {
                        tempStrBuilder.Replace("@Content@", "<div id=\"ShowContent\"></div>"); //当前页的问题内容
                    }

                }
                else//没有手工分页又没有自动分页设置，就直接显示所有问题内容
                {
                    tempStrBuilder.Replace("@Page@", "");

                    if (this.Model.Rank == 0)
                    {
                        tempStrBuilder.Replace("@Content@", strContent);
                    }
                    else
                    {
                        tempStrBuilder.Replace("@Content@", "<div id=\"ShowContent\"></div>"); //当前页的内容
                    }

                }
            }
            #endregion

            return tempStrBuilder.ToString();
        }
        #endregion

        #region 重写Render
        protected override void Render(HtmlTextWriter writer)
        {
            StringBuilder winner = new StringBuilder();
            using (TextWriter tempWriter = new StringWriter())
            {
                base.Render(new HtmlTextWriter(tempWriter));
                winner.Append(tempWriter.ToString());
            }

            #region 通用模型标签


            IList<string> matchresult = TagEngine.TagCollection(winner.ToString(), "Annex");
            foreach (string nextmatch in matchresult)
            {
                string annexString = PageCommon.AnnexList(nextmatch, this.ArticleId);

                winner.Replace(nextmatch, annexString);
            }

            ArticleCommon.PNArticle(winner, this.ArticleId);


            CategoryCommon.Path(winner, CategoryId);

            if (Request["Method"] != null)
            {
                FileIO fileio = new FileIO();
                int pageCount = ArticleCommon.ArticlePageCount(this.Model.Content);
                string webString = winner.ToString();

                for (int p = 1; p < pageCount + 1; p++)
                {
                    StringBuilder temp = new StringBuilder(webString);

                    temp.Replace(MyString.GetString(webString, "<TW:Context>", "</TW:Context>"), ContextBuilder(MyString.GetInnerString(webString, "<TW:Context>", "</TW:Context>"), p));

                    string path = StaticFilePath.ContentShowUrl(this.Model, p);

                    temp.Replace("@PageNo@", p.ToString());

                    fileio.WriterFile(HttpServer.MapPath(path), temp.ToString());
                }

                writer.Write(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:ffff"));
            }
            else
            {
                winner.Replace("@PageNo@", this.PageNo.ToString());

                ArticleContext(winner);

                PageCommon.RepalceFiled(winner, this.Model);

                writer.Write(winner.ToString());
            }
            #endregion
        }
        #endregion

        public override void FillClassInfo()
        {
            this.CategoryId = Model.CategoryId;
        }
    }
}